<template>
    <el-row id="myRow1">
        <p id="myP1_left">
            <el-icon><Fold /></el-icon>
            <span style="color: #000;">客服</span>
            <span>/</span>
            <span>用户提现</span>
        </p>
        <p></p>
    </el-row>
    <el-row id="myRow2">
        <div style="height: 2em;width: 6.5em;background-color: #46BA85;font-size: 12px;display: flex;justify-content: center;align-items: center;color: white;gap: 2px;">
            <div style="width: 0.8em;height: 0.8em;border-radius: 0.4em;background-color: white;"></div>
            <div>用户提现</div>
            <el-icon><CloseBold /></el-icon>
        </div>
    </el-row>
    <el-form :inline="true" :model="myForm" id="myForm">
        <el-form-item>
            <el-input placeholder="请选择姓名" v-model="myForm.gongsi"></el-input>
        </el-form-item>
        <el-form-item>
            <el-input placeholder="设备编号" v-model="myForm.code"></el-input>
        </el-form-item>
        <el-form-item>
            <el-input placeholder="设备地址" v-model="myForm.address"></el-input>
        </el-form-item>
        <el-form-item>
            <el-input placeholder="请输入手机号" v-model="myForm.nickname"></el-input>
        </el-form-item>
        <el-form-item>
            <div class="demo-date-picker">
                <div class="block">
                <el-date-picker
                    v-model="myForm.value1"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间" 
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
                </div>
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
    </el-form>
    <el-row id="myRow3">
        <el-button type="info" style="margin-bottom: 1em;" @click="handleRefresh"><el-icon><Refresh /></el-icon>刷新</el-button>
    </el-row>
    <el-table style="width: 100%;" border :data="tableData" 
    row-key="id"
    >
        <el-table-column type="selection" prop="select" width="40" />
        <el-table-column label="姓名" prop="nickname"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="兑换比例（积分/现金）" prop="exchange_rate"></el-table-column>
        <el-table-column label="消费积分" prop="consumer_points"></el-table-column>
        <el-table-column label="申请提现金额/元" prop="amount"></el-table-column>
        <el-table-column label="体现平台" prop="withdrawal_platform"></el-table-column>
        <el-table-column label="来源" prop="source"></el-table-column>
        <el-table-column label="申请时间" prop="apply_time"></el-table-column>
        <el-table-column label="常投小区" prop="hotspot_area"></el-table-column>
        <el-table-column label="操作">
            <template #default="scoped">
                <el-button :type="getRowButtonType(scoped.row.status)" @click="handleToReview(scoped.row)">
                    {{ getStatusText(scoped.row.status) }}
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 审核模态框 -->
    <el-dialog v-model="dialogEdit">
        <el-row style="font-size: 20px;position: relative;bottom: 1em;width: 10em;">提现审核</el-row>
        <el-row style="margin-top: 2em;font-size: 16px;border-bottom: 2px solid #ccc;">
            <el-col :span="4" style="padding-bottom: 1em;color: #69AEFC;border-bottom: 2px solid #69AEFC;position: relative;top: 1px;cursor: pointer;" @click="myClickOne($event)">提现信息</el-col>
            <el-col :span="4" style="padding-bottom: 1em;position: relative;top: 1px;cursor: pointer;" @click="myClickTwo($event)">投递记录</el-col>
        </el-row>
        <el-form :model="myFormOne" label-width="auto" v-if="flag == 0">
            <el-form-item label="申请人" class="myFormItem1" style="margin-top: 1em;">
                <el-input disabled="true" v-model="myFormOne.nickname"></el-input>
            </el-form-item>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="申请提现金额">
                        <el-input disabled="true" v-model="myFormOne.amount"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="1">元</el-col>
            </el-row> 
            <el-form-item label="申请时间" class="myFormItem1">
                <el-input disabled="true" v-model="myFormOne.apply_time"></el-input>
            </el-form-item>
            <el-form-item label="审核状态" class="myFormItem1">
                <el-select v-model="myFormOne.status">
                     <el-option 
                        v-for="item in statusOptions" 
                        :key="item.code" 
                        :label="item.label" 
                        :value="item.code"  
                ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注">
                <el-input type="textarea"
                v-model="myFormOne.note"
                ></el-input>
            </el-form-item>
            <el-row style="justify-content: flex-end">
                <el-button @click="dialogEdit = false">取消</el-button>
                <el-button type="primary" @click="submitReview">确定</el-button>
            </el-row>
        </el-form>
        <el-form :model="myFormOne" label-width="auto" v-if="flag == 1">
            <el-table style="width: 100%;" border :data="tableDatas" >
                <el-table-column label="昵称" prop="nickname"></el-table-column>
                <el-table-column label="设备编号" prop="device_code"></el-table-column>
                <el-table-column label="设备地点" prop="equipment_location"></el-table-column>
                <el-table-column label="投递重量/kg" prop="weight"></el-table-column>
                <el-table-column label="金额/元" prop="reward"></el-table-column>
                <el-table-column label="投递时间" prop="review_time"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scoped"><el-button type="primary" @click="handleOpenBalance(scoped.row)">余额变更</el-button></template>
                </el-table-column>
              </el-table>
             <!-- 分页区域 -->
                <div class="footer">
                    <span>共4条</span>
                    <div class="flex flex-wrap items-center">
                        <el-dropdown>
                        <el-button type="primary">
                        5条/页<el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                            <el-dropdown-item>Action 1</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    </div>
                        <div>
                            <hr class="my-4" />
                            <el-pagination
                            background
                            :total="5"
                            layout="prev, pager, next"
                            />
                        </div>
                    前往<div class="btn">1</div>页
                </div>
        </el-form>
    </el-dialog>
    <el-dialog v-model="dialogBalance">
        <el-row style="font-size: 20px;position: relative;bottom: 1em;width: 10em;">余额变更</el-row>
        <el-form :model="balanceForm" label-width="auto">
            <el-form-item label="原重量/kg" class="myFormItem1">
                <el-input :disabled="true" v-model="balanceForm.weight"></el-input>
            </el-form-item>
            <el-form-item label="变更类型" class="myFormItem1" >
                <el-select  v-model="balanceForm.changeType">
                    <el-option label="扣除"  value="1"></el-option>
                    <el-option label="补偿" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item   label="变更重量/kg" required class="myFormItem1">
                <el-input v-model="balanceForm.changeWeight"></el-input>
            </el-form-item>
            <el-form-item label="原因">
                <el-input 
                 v-model="balanceForm.reason" 
                type="textarea"
                ></el-input>
            </el-form-item>
             <el-form-item label="图片" required>
                <el-upload
                    class="upload-demo"
                    action="#"
                     :auto-upload="false"
                    :file-list="fileList"
                    :on-remove="handleRemove"
                    :on-change="handleFileChange"
                    :http-request="handleHttpRequest"
                    accept="image/*"
                    :multiple="false"  
                >
                    <div v-if="fileList.length === 0" class="upload-plus">
                    <el-icon class="plus-icon"><Plus /></el-icon>
                    <div class="plus-text">点击上传</div>
                    </div>
                    <div v-else class="uploaded-image">
                    <img :src="fileList[0].url" class="uploaded-img" />
                    <el-icon class="remove-icon" ><Delete /></el-icon>
                    </div>
                </el-upload>
            </el-form-item>
            <el-row style="justify-content: flex-end">
                <el-button @click="dialogBalance = false">取消</el-button>
                <el-button type="primary" @click="handleSuccess">确定</el-button>
            </el-row>
        </el-form>
    </el-dialog>
</template>

<script setup>
    import { reactive,ref,onMounted,computed, onUnmounted} from 'vue';
    import axios from 'axios';
    import {
        getDrawalList, getDrawalListReview
    } from '@/components/api/UserCash'
     import {
      getDeliverList
    } from '@/components/api/DeliverRecord'
     import {    ElPageHeader, 
                ElInput, 
                ElSelect, 
                ElOption, 
                ElButton,
                ElAvatar,
                ElDropdown,
                ElDropdownMenu,
                ElDropdownItem,
                ElPagination,
                ElIcon,
                ElMessage
            } from 'element-plus';
    const fileList = ref([]);
    //列表
    let dialogEdit = ref(false)
    let dialogBalance = ref(false)
    let myForm = reactive({
        gongsi:'',
        shoujihao:'',
        juese:'',
        zhuangtai:'',
        value1:[],
        code:''
    })
    let tableData = ref([])
    
    // 状态下拉选项
    let statusOptions = ref([
        { code: 0, label: '待审核' },
        { code: 1, label: '通过' },
        { code: 2, label: '拒绝' },
        { code: 3, label: '打款中' },
        { code: 4, label: '失败' }
    ]);
    
    // 根据状态码获取对应的文本
    const getStatusText = (statusCode) => {
        const option = statusOptions.value.find(opt => opt.code === statusCode);
        return option ? option.label : '审核';
    };
    
    // 根据行的状态获取按钮类型（用于表格中的按钮）
    const getRowButtonType = (statusCode) => {
        switch(statusCode) {
            case 1: return 'success'; // 通过 - 成功色
            case 2: return 'warning';  // 拒绝 - 警告色
            case 3: return 'info';    // 打款中 - 信息色
            case 4: return 'danger'; // 失败 - 危险色
            default: return 'primary'; // 待审核 - 主色
        }
    };

    // 计算属性：根据状态返回操作文本（用于模态框中的按钮）
    const operationText = computed(() => {
        switch(myFormOne.value.status) {
            case 0: return '审核';
            case 1: return '通过';
            case 2: return '拒绝';
            case 3: return '打款';
            case 4: return '标记失败';
            default: return '确定';
        }
    });
    
    // 计算按钮类型
    const buttonType = computed(() => {
        switch(myFormOne.value.status) {
            case 1: return 'success'; // 通过 - 成功色
            case 2: return 'danger';  // 拒绝 - 危险色
            case 3: return 'info';     //打款 - 等待
            case 4: return 'warning'; // 失败 - 警告色
            default: return 'primary';
        }
    });
    
    //用户提现列表
    let drawalList = ref([])
    let getDrawalListFun = () => {
        const drawalListData = {
            pageIndex:parseInt(1),
            pageSize:parseInt(10),
        }
        getDrawalList(drawalListData)
        .then(res => {
            if(res.code == 200){
                drawalList.value = res.dataset.list
                tableData.value=drawalList.value 
            }
        })
    }
    
    // 刷新函数
    const handleRefresh = () => {
        getDrawalListFun()
        ElMessage.success('数据已刷新')
    }
    
    // 代审核接口
    let myFormOne = ref({
        nickname:'',
        apply_time:'',
        status:0,
        note:'',
        amount:'',
        id:'',
        deliverRecordId:''
    })
    
    const handleToReview = (row) => {
        myFormOne.value.id = row.id; 
        myFormOne.value.amount = row.amount;
        myFormOne.value.nickname = row.nickname;
        myFormOne.value.apply_time = row.apply_time; 
        myFormOne.value.status = row.status  || 0;
        myFormOne.value.deliverRecordId = row.id; 
        dialogEdit.value = true;
    };
    
    // 提交审核结果
    const submitReview = () => {
        const submitData = {
            id: myFormOne.value.id, 
            status: myFormOne.value.status, 
            note: myFormOne.value.note, 
        };
        getDrawalListReview(submitData)
            .then(res => {
            if (res.code === 200) {
                ElMessage.success('操作成功');
                dialogEdit.value = false; 
                getDrawalListFun(); 
                
                // 设置刷新标志，通知第二个组件
                localStorage.setItem('withdrawalLastUpdate', new Date().getTime().toString());
                
                // 如果第二个组件的全局函数存在，直接调用
                if (window.updateWithdrawalHistory) {
                    window.updateWithdrawalHistory();
                }
            } else {
                ElMessage.error(res.msg || '操作失败');
            }
        })
    };
    
    onMounted(() => {
        getDrawalListFun();
        getDrawalListReviewFunReview()
    });
    
    // 点击搜索执行搜索
    const handleSearch =()=>{
         const drawalListData = {
            pageIndex: parseInt(1),
            pageSize: parseInt(10),  
            gongsi: myForm.gongsi,     
            deviceCode: myForm.code,       
            nickname: myForm.nickname, 
        };
        getDrawalList(drawalListData)
            .then(res => {
            if(res.code === 200){
                drawalList.value = res.dataset.list;
                tableData.value = drawalList.value;
            }
        })
    }
    
    let flag = ref(0);
    let myClickOne = (e) => {
        e.target.style.color = "#69AEFC";
        e.target.style.borderBottom = "2px solid #69AEFC";
        e.target.nextElementSibling.style.color = "#000";
        e.target.nextElementSibling.style.borderBottom = "0px"
        flag.value = 0;
    }
    
    let myClickTwo = (e) => {
        e.target.style.color = "#69AEFC";
        e.target.style.borderBottom = "2px solid #69AEFC";
        e.target.previousElementSibling.style.color = "#000";
        e.target.previousElementSibling.style.borderBottom = "0px";
        flag.value = 1;
        getDrawalListReviewFunReview()
    }
    
    // 投递记录
    let tableDatas = ref([])
    
    let getDrawalListReviewFunReview = () => {
        const drawalListDataReview = {
            pageIndex:parseInt(1),
            pageSize:parseInt(10),
            id:myFormOne.value.deliverRecordId
        }
        getDeliverList(drawalListDataReview)
        .then(res => {
            if(res.code == 200){
                tableDatas.value =res.dataset.list; 
            }
        })
    }

    // 余额变更模态框
    let balanceForm = ref({
        id:'',
        weight: '',
        changeType: '1', 
        changeWeight: '', 
        reason: '',
        imagePaths:''
    });
    
    // 打开余额变更模态框，并赋值投递记录数据
    const handleOpenBalance = (deliverRow) => {
        balanceForm.value.weight = deliverRow.weight;
        balanceForm.value.id = deliverRow.id;
        fileList.value = [];
        balanceForm.value.changeType = '1';
        balanceForm.value.changeWeight = '';
        balanceForm.value.reason = '';
        dialogBalance.value = true;
    };
    
    const handleSuccess = () => {
        if (!balanceForm.value.changeType || balanceForm.value.changeType === '0') {
            ElMessage.warning('请选择变更类型（扣除或补偿）！');
            return;
        }
        if (!balanceForm.value.changeWeight) {
            ElMessage.warning('请输入变更重量！');
            return;
        }
        if (!balanceForm.value.reason) {
            ElMessage.warning('请输入变更原因！');
            return;
        }
        if (fileList.value.length === 0) {
            ElMessage.warning('请先上传图片！');
            return;
        }
        if (!fileList.value[0] || !fileList.value[0].raw) {
            ElMessage.warning('图片格式错误，请重新上传！');
            fileList.value = []; 
            return;
        }
        const formData = new FormData();
        formData.append('id', balanceForm.value.id); 
        formData.append('change_type', Number(balanceForm.value.changeType)); 
        formData.append('change_weight', Number(balanceForm.value.changeWeight)); 
        formData.append('reason', balanceForm.value.reason);
        formData.append('imagePaths', fileList.value[0].raw,fileList.value[0].name);
        axios.post('http://106.13.143.56:8080/garbageSys/delivery/update2', formData, {
            headers: {
                'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwicGFzc3dvcmQiOiJhZG1pbiIsImF2YXRhciI6bnVsbCwic3RhdHVzIjoxLCJjcmVhdGVkQXQiOiIyMDI1LTA5LTI5IDExOjMxOjQwIiwidXBkYXRlZEF0IjoiMjAyNS0xMC0xMyAxNzo1MzoyMiIsInBob25lIjoiMTIzNDU2Nzg5MDEiLCJkZWxpdmVyeVRvdGFsIjpudWxsLCJwb2ludHNUb3RhbCI6bnVsbCwibGFzdEFjdGl2aXR5VGltZSI6bnVsbH0sImlhdCI6MTc2MDM1MzEzN30.CZKn_nbSyFOlTajUhwje0dRgOzPUxFcvHCwJlKFt1az7gncuBbqq1GFvgpTMq1dKdYoOkYn0CAJJnhx9EaoQ7Q',
                'Content-Type':'multipart/form-data'
            }
        })
        .then(res => {
            if (res.data.code === 200) {
                ElMessage.success('图片上传成功，余额变更已提交！');
                dialogBalance.value = false; 
                getDrawalListReviewFunReview(); 
                fileList.value = [];
                balanceForm.value = { id: '', weight: '', changeType: '0', changeWeight: '', reason: '' };
            } else {
                ElMessage.error(`上传失败: ${res.data.msg}`);
            }
        })
    };
    
    const handleRemove = (uploadFile, uploadFiles) => {
        fileList.value = uploadFiles; 
    };
    
    const handleFileChange = (file, uploadFiles) => {
        const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (!allowedTypes.includes(file.raw.type)) {
            ElMessage.error('请上传 JPG、PNG 或 WebP 格式的图片！');
            fileList.value = uploadFiles.filter(f => f.uid !== file.uid);
            return;
        }
        if (file.raw) {
            file.url = URL.createObjectURL(file.raw);
        }
        fileList.value = fileList.value;
    };
    
    const handleHttpRequest = () => {
    };
</script>

<style scoped lang="less">
    #myRow1{
        border-bottom: 1px solid #ccc;
        padding: 0 1em;
        box-sizing: border-box;
        height: 3em;
        display: flex;
    }
    #myP1_left{
        height: 100%;
        display: flex;
        align-items: center;
        margin: 0;
        span{
            font-size: 14px;     
            margin-left: 0.7em;  
            color: #9AAABF; 
        }
    }
    #myRow2{
        height: 40px;
        align-items: center;
        padding: 0 1em;
        border-bottom: 1px solid #ccc;
    }
    #myForm{
        padding-left: 1.2em;
        padding-top: 1.3em;
        .el-form-item{
            width: 13%;
        }
        button{
            margin-left: 12em;
        }
    }
    #myRow3{
        justify-content: flex-end;
        padding: 0 1em;
    }
    .myFormItem1{
        width: 45%;
    }
    .myFormItem2{
        width: 85%;
    }
    .el-form-item__content{
        flex-wrap: nowrap
    }
     .footer{
            width: 829px;
            height: 36px;
            float: left;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            background-color: #fff;
            margin-left: -16px;
            .el-button--primary{
                background-color: #fff;
                color: #333;
            }
            .el-pager{
                font-size: 15px;
            }
            .btn{
                width: 38px;
                height: 20px;
                border: 1px solid #ccc;
                display: flex;
                justify-content: center;
                align-items: center;
            }
    }
     .upload-demo {
        display: inline-block;
        }
        .upload-plus {
        width: 120px;
        height: 80px;
        border: 1px dashed #dcdcdc;
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        }
        .plus-icon {
        font-size: 24px;
        color: #999;
        }
        .plus-text {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
        }
        .uploaded-image {
        position: relative;
        width: 120px;
        height: 80px;
        }
        .uploaded-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 4px;
        }
        .remove-icon {
        position: absolute;
        top: -10px;
        right: -10px;
        background-color: #fff;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
        }
</style>